﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;

namespace BGSpaceShooterServer
{
    internal class UDPMessenger
    {
        private IPAddress targetIP;
        private int targetPort;

        public UDPMessenger(IPAddress ipAddress, int port)
        {
            targetIP = ipAddress;
            targetPort = port;
        }

        public void SendMessage(ServerToClientPacket serverToClientPacket)
        {
            int rawsize = Marshal.SizeOf(serverToClientPacket);
            IntPtr buffer = Marshal.AllocHGlobal(rawsize);
            Marshal.StructureToPtr(serverToClientPacket, buffer, false);
            byte[] rawdatas = new byte[rawsize];
            Marshal.Copy(buffer, rawdatas, 0, rawsize);
            Marshal.FreeHGlobal(buffer);

            UdpClient udpClient = new UdpClient();
            udpClient.Connect(targetIP, targetPort);

            udpClient.Send(rawdatas, rawsize);

            udpClient.Close();
        }
    }
}
